package com.hmall.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(RabbitTemplate.class)
public class MqConfig {

    /**
     * 设置消息转换器
     *
     * @return
     */
   /* @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }*/
    @Bean
    public MessageConverter messageConverter() {

        return new Jackson2JsonMessageConverter() {
            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                //判断消息不为空
                if (ObjectUtil.isNotNull(message)) {
                    //从消息头中取出用户信息
                    Long userId = message.getMessageProperties().getHeader("user-info");
                    //存入线程中
                    UserContext.setUser(userId);
                }
                return super.fromMessage(message);
            }
        };

    }
}
